package com.hwhhhh.graduationproject.service.impl;

import com.hwhhhh.graduationproject.controller.param.UserReq;
import com.hwhhhh.graduationproject.dao.repo.UserRepo;
import com.hwhhhh.graduationproject.domain.model.User;
import com.hwhhhh.graduationproject.dao.entity.UserEntity;
import com.hwhhhh.graduationproject.exception.InvalidAccountException;
import com.hwhhhh.graduationproject.service.UserService;
import com.hwhhhh.graduationproject.utils.JWTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description detail
 * Created by Hwhhhh on 2021/3/2 19:00
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepo userRepo;

    /**
     * 还可进一步细分用户存在与否，密码是否正确
     * @param userReq
     * @return
     * @throws Exception 用户名或密码错误；用户被封禁
     */
    @Override
    public User login(UserReq userReq) throws Exception {
        UserEntity userEntity = userRepo.findByEmailAndPassword(userReq.getEmail(), userReq.getPassword());
        if (userEntity != null) {
            if (userEntity.getIsEffective() == 0) throw new InvalidAccountException("用户已被封禁！请联系管理员！");
            User user = new User();
            BeanUtils.copyProperties(userEntity, user);
            return user;
        } else {
            throw new NullPointerException("用户名或密码错误！");
        }
    }

    @Override
    public boolean checkEmail(String email) {
        if (this.userRepo.findByEmail(email) == null) return false; // 不存在返回false
        return true;
    }

    @Override
    public String register(UserReq userReq) {
        UserEntity userEntity = new UserEntity();
        //设置email和pwd并保存，完成注册
        userEntity.setEmail(userReq.getEmail());
        userEntity.setPassword(userReq.getPassword());
        UserEntity newUser =  userRepo.save(userEntity);
        // 生成token用于直接登录
        Map<String, String> map = new HashMap<>();
        map.put("id", Integer.toString(newUser.getId()));
        map.put("isAd", Integer.toString(newUser.getIsAd()));

        return JWTUtils.generateToken(map);
    }

    @Override
    public void updateUserInfo(UserReq userReq, int userId) throws Exception{
        UserEntity entity = this.userRepo.findById(userId);
        if (entity == null) throw new Exception("服务器异常！");
        BeanUtils.copyProperties(userReq, entity);
    }

    @Override
    public void uploadProfilePhoto(int userId, String url) throws Exception {
        UserEntity entity = this.userRepo.findById(userId);
        if (entity == null) throw new Exception("服务器异常！");
        entity.setProfilePhoto(url);
        this.userRepo.save(entity);
    }
}
